// ingress.go
package controllers

import (
	"log"
	m "myk8s/models"
	"strings"

	//"github.com/tidwall/gjson"

	beego "github.com/beego/beego/v2/server/web"
)

type IngressController struct {
	beego.Controller
}

func (this *IngressController) List() {
	clusterId := this.GetString("clusterId")
	nameSpace := this.GetString("nameSpace")
	ingressName := this.GetString("ingressName")
	serviceName := this.GetString("serviceName")
	labels := this.GetString("labels")
	labelsKV := strings.Split(labels, ":")
	var labelsKey, labelsValue string
	if len(labelsKV) == 2 {
		labelsKey = labelsKV[0]
		labelsValue = labelsKV[1]
	}
	ingressList, err := m.IngList(clusterId, nameSpace, ingressName, serviceName, labelsKey, labelsValue)
	msg := "success"
	code := 0
	count := len(ingressList)
	if err != nil {
		log.Println(err)
		msg = err.Error()
		code = -1
	}

	this.Data["json"] = &map[string]interface{}{"code": code, "msg": msg, "count": count, "data": &ingressList}
	this.ServeJSON()
}

func (this *IngressController) Create() {
	clusterId := this.GetString("clusterId")
	msg := "success"
	code := 0
	err := m.IngCreate(clusterId, this.Ctx.Input.RequestBody)
	if err != nil {
		log.Println(err)
		msg = err.Error()
		code = -1
	}
	this.Data["json"] = &map[string]interface{}{"code": code, "msg": msg}
	this.ServeJSON()
}

func (this *IngressController) ModifyByYaml() {
	clusterId := this.GetString("clusterId")
	//nameSpace := gp.Get("nameSpace").String()
	log.Println(string(this.Ctx.Input.RequestBody))
	bodyByte := []byte(strings.ReplaceAll(string(this.Ctx.Input.RequestBody), "%25", "%"))
	err := m.IngYamlModify(clusterId, bodyByte)
	if err != nil {
		log.Println(err)
	}
	this.Data["json"] = &map[string]interface{}{"code": 0, "msg": "ok"}
	this.ServeJSON()
}

func (this *IngressController) Yaml() {
	clusterId := this.GetString("clusterId")
	namespace := this.GetString("nameSpace")
	ingressName := this.GetString("ingressName")

	yamlStr, _ := m.GetIngYaml(clusterId, namespace, ingressName)
	this.Ctx.WriteString(yamlStr)
}
